const db = require('../db')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const { nanoid } = require('nanoid')
const dayjs = require('dayjs')

const config = require('../utils/config')
const { getNowTime, formatTime } = require('../utils')
const { addLogin_log } = require('./login_log')
const { addOperation_log } = require('./operation_log')

/**
 * 注册
 * @param {*} req 请求参数
 * @param {*} res 响应参数
 */
exports.regUser = (req, res) => {
   // 开始时间
   const startTime = dayjs()
  const { username, email, password, password_verify } = req.body
  //   校验密码是否一致
  if (password !== password_verify) {
    return res.new_send('两次输入的密码不一致！')
  }
  // 查询用户
  const selectSql = `select * from sys_user where username = ?`
  db.query(selectSql, username, (err, results) => {
    if (err) return res.new_send(err)
    if (results.length > 0) return res.new_send('用户名已存在！')
    // 密码加密
    let password_bcrypt = bcrypt.hashSync(password, 10)
    // 插入数据库
    const insertsql = 'insert into sys_user set ?'
    db.query(
      insertsql,
      {
        username,
        password: password_bcrypt,
        nick_name: '用户' + nanoid(5),
        sex: null,
        email,
        mobile: null,
        avatar: '/default/1.jpg',
        create_time: getNowTime(),
        status: true,
        remark: '用户注册',
        is_admin: false,
        is_delete: 0
      },
      (err, results) => {
        if (err) return res.new_send(err)
        // console.log(results.insertId, "注册-获取用户Id");
        if (results.affectedRows !== 1) return res.new_send('注册用户失败')
        // 结束时间
        const endTime = dayjs()
        const difftime = endTime.diff(startTime) // 时间差
        // 处理操作日志表
        addOperation_log(req, res, { time: difftime, userId: '' })
        res.new_send('注册成功', 0)
      }
    )
  })
}

/**
 * 登录
 * @param {*} req 请求参数
 * @param {*} res 响应参数
 */
exports.login = (req, res) => {
  // 开始时间
  const startTime = dayjs()

  const { username, password } = req.body
  // 查询用户(非删除)
  const selectSql = `select * from sys_user where username = ? and is_delete = 0`
  db.query(selectSql, username, (err, results) => {
    if (err) return res.new_send(err)
    if (results.length <= 0) return res.new_send('用户不存在')
    // 密码对比
    const compareResult = bcrypt.compareSync(password, results[0].password)
    if (!compareResult) return res.new_send('密码错误')
    // 生成Token
    const user = { ...results[0], password: '', avatar: '' }
    user.create_time = formatTime(user.create_time)
    const tokenStr = jwt.sign(user, config.jwtSecretKey, {
      expiresIn: config.expiresIn
    })
    // 结束时间
    const endTime = dayjs()
    const difftime = endTime.diff(startTime) // 时间差

    // 处理登录日志表
    addLogin_log(req, res, {
      time: difftime,
      status: 'online',
      userId: user.id
    })
    res.send({
      status: 0,
      message: '登录成功',
      token: 'Bearer ' + tokenStr,
      user
    })
  })
}
